//
//  EmoticonView.swift
//  表情键盘
//
//  Created by 孙明海 on 16/2/16.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import UIKit

//可重用 cell ID 
private let EmoticonViewCellID = "EmoticonViewCellID"

class EmoticonView: UIView {

    //MARK: - 监听方法
    @objc private func clickItem(item: UIBarButtonItem) {
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
    
    private var selectEmoticonCallback: (emoticon: Emoticon) -> ()
    
    //MARK: - 构造函数
    init(selectEmoticonCallback: (emoticon: Emoticon) -> ()) {
        
        self.selectEmoticonCallback = selectEmoticonCallback
        
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 226
        super.init(frame: rect)
        setUI()
        
        //默认滚动到第一页
        //当主线程上的代码执行完成后才会执行下面的代码,此时collectionView 已创建并布局完成
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            let indexPath = NSIndexPath(forItem: 0, inSection: 1)
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 懒加载控件
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonLayout())
    private lazy var toolbar: UIToolbar = UIToolbar()
    //表情包数组
    private lazy var packages = EmoticonManager.sharedManager.packages
    
    /// 表情键盘布局
    private class EmoticonLayout: UICollectionViewFlowLayout {
        private override func prepareLayout() {
            super.prepareLayout()
            let col: CGFloat = 7
            let row: CGFloat = 3
            let w = (collectionView?.bounds.width)! / col
            let margin = ((collectionView?.bounds.height)! - row * w) * 0.499
            itemSize = CGSize(width: w, height: w)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            scrollDirection = .Horizontal
            collectionView?.showsHorizontalScrollIndicator = false
            collectionView?.bounces = false
            collectionView?.pagingEnabled = true
        }
    }
}
// MARK: - 设置界面
private extension EmoticonView {
    /// 设置界面
    func setUI() {
        //添加子控件
        addSubview(collectionView)
        addSubview(toolbar)
        toolbar.backgroundColor = UIColor.blueColor()
        
        //自动布局
        toolbar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self)
            make.bottom.equalTo(self)
            make.right.equalTo(self)
            make.height.equalTo(44)
        }
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self)
            make.left.equalTo(self)
            make.bottom.equalTo(toolbar.snp_top)
            make.right.equalTo(self)
        }
        
        //准备控件
        prepareToolbar()
        prepareCollectionView()
    }
    //准备工具栏
    func prepareToolbar() {
        //设置渲染颜色
        toolbar.tintColor = UIColor.darkGrayColor()
        
        //设置按钮内容
        let arr = ["最近", "默认", "emoji", "浪小花"]
        var items = [UIBarButtonItem]()
        var index = 0
        for s in arr {
            items.append(UIBarButtonItem(title: s, style: .Plain, target: self, action: "clickItem:"))
            items.last?.tag = index++
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        //设置items
        toolbar.items = items
    }
    //准备collectioinView
    func prepareCollectionView() {
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: EmoticonViewCellID)
        collectionView.dataSource = self
        collectionView.delegate = self
    }
}

// MARK: - UICollectionViewDataSource,UICollectionViewDelegate
extension EmoticonView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let emoticon = packages[indexPath.section].emoticons[indexPath.item]
        if indexPath.section > 0 {
            EmoticonManager.sharedManager.addFavorite(emoticon)
        }
        selectEmoticonCallback(emoticon: emoticon)
    }
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonViewCellID, forIndexPath: indexPath) as! EmoticonViewCell

        cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
        return cell
    }
}
/// 表情视图 cell
private class EmoticonViewCell: UICollectionViewCell {
    
    var emoticon: Emoticon? {
        didSet {
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: .Normal)
            emoticonButton.setTitle(emoticon?.emoji, forState: .Normal)
            
            if emoticon!.isRemoved {
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
            }
        }
    }
    
    /// 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(emoticonButton)
        emoticonButton.backgroundColor = UIColor.whiteColor()
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        
        //设置titleLable 的字体大小
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        //禁用button,让cell去处理点击事件
        emoticonButton.userInteractionEnabled = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 懒加载控件
    private lazy var emoticonButton: UIButton = UIButton()
}






